package
{
	import flare.animate.Tween;
	import flare.display.RectSprite;
	import flare.display.TextSprite;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	public class Variable extends RectSprite
	{
		public static var BOX_WIDTH:Number = 105;
		public static var BOX_HEIGHT:Number = 20;
		public static var BOX_START_X:Number = 50;
		public static var BOX_START_Y:Number = 50;
		public static var BOX_MARGIN:Number = 10;
		public static var BOX_PADDING:Number = 3;
		
		private var text:String;
		private var value:RectSprite;
		private var valueString:String;
		private var startX:Number;
		private var startY:Number;
		private var locked:Boolean;
		
		public function Variable(name:String, position:Number)
		{
			super(BOX_START_X, BOX_START_Y + position * (BOX_HEIGHT + BOX_MARGIN),
				BOX_WIDTH, BOX_HEIGHT);
			this.startX = x;
			this.startY = y;
			this.text = name;
			this.fillColor = 0xffffffff;
			this.buttonMode = true;
			this.locked = false;
			
			var ts:TextSprite = new TextSprite(text);
			ts.x = BOX_PADDING;
			ts.y = BOX_PADDING;
			ts.bold = true;
			
			var bg:RectSprite = new RectSprite(0,0,BOX_WIDTH,BOX_HEIGHT);
			bg.fillColor = 0xffffffff;
			
			value = new RectSprite(0,0,BOX_WIDTH,BOX_HEIGHT);
			value.fillColor = 0xffffffff;
			var t:TextSprite = new TextSprite();
			t.x = Variable.BOX_PADDING;
			t.y = Variable.BOX_PADDING;
			t.color = 0xff444444;
			t.size = 11;
			t.bold = true;
			value.addChild(t);
			
			this.addChild(value);
			this.addChild(bg);
			this.addChild(ts);
			
			makeDraggable();
		}
		
		public function setValue(theValue:String):void
		{
			locked = true;
			valueString = theValue;
			(value.getChildAt(0) as TextSprite).text = theValue;
			var twn:Tween = new Tween(value, 0.5, {y:Variable.BOX_HEIGHT});
			twn.play();
		}
		
		public function clearValue():void
		{
			locked = false;
			valueString = "";
			(value.getChildAt(0) as TextSprite).text = "";
			var twn:Tween = new Tween(value, 0.5, {y:0});
			twn.play();
		}
		
		public function getText():String
		{
			return text;
		}
		
		public function getValue():String
		{
			return (value.getChildAt(0) as TextSprite).text;
		}
		
		public function reset():void
		{
			x = startX;
			y = startY;
		}
		
		public function isLocked():Boolean
		{
			return locked;
		}
		
		private function makeDraggable():void
		{
			addEventListener(MouseEvent.MOUSE_DOWN,
				function(evt:Event):void {
					if (!locked) {
						evt.currentTarget.startDrag();
					}
				}
			);
				
			addEventListener(MouseEvent.MOUSE_UP,
				function(evt:Event):void {
					if (!locked) {
						evt.currentTarget.stopDrag();
					}
				}
			);
		}

	}
}